//
//  ShopListController.m
//  KingSelected
//
//  Created by 杨鹏 on 2023/11/5.
//

#import "ShopListController.h"
#import "ShopModel.h"
#import "ShopTableView.h"
#import "PublishShopViewController.h"
#import "ShopInfoViewController.h"
#import "UpdateTipsView.h"
#import "GoodsQrCodeViewController.h"
#import "ShopManagerBottomView.h"

@interface ShopListController ()

@property (nonatomic, strong) NSMutableArray *modelArr;
@property (nonatomic, strong) ShopTableView *tableview;
@property (nonatomic, assign) NSInteger lastIndex;
@property (nonatomic, copy) NSString *searchStr;
@property (nonatomic, assign) BOOL isEditShop;
@property (nonatomic, strong) ShopManagerBottomView *bottomView;
@property (nonatomic, strong) NSMutableArray *selectedArr;

@end

@implementation ShopListController

- (void)setModel:(UserModel *)model {
    _model = model;
}

- (void)setShopEditing:(BOOL)isEdit {
    self.isEditShop = isEdit;
    [self.tableview setEditing:isEdit animated:YES];
    if (isEdit) {
        self.bottomView.hidden = NO;
        [UIView animateWithDuration:0.3 animations:^{
            self.bottomView.alpha = 1;
        }];
        if (_tableview.frame.size.width > 0) {
            [self.tableview mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.edges.mas_equalTo(UIEdgeInsetsMake(0, 0, 70, 0));
            }];
        }
        
    }else {
        [UIView animateWithDuration:0.3 animations:^{
            self.bottomView.alpha = 0;
        }completion:^(BOOL finished) {
            self.bottomView.hidden = YES;
        }];
        if (_tableview.frame.size.width > 0) {
            [self.tableview mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.edges.mas_equalTo(UIEdgeInsetsMake(0, 0, 0, 0));
            }];
        }
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.lastIndex = 0;
    [self requestData];
}

- (void)initViews {
    self.view.backgroundColor = kRGB(0xF7F7F7);
    [self.view addSubview:self.tableview];
    if (self.isEditShop) {
        [self.tableview mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_equalTo(UIEdgeInsetsMake(0, 0, 70, 0));
        }];
    }else {
        [self.tableview mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_equalTo(0);
        }];
    }
    
    [self.view addSubview:self.bottomView];
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.bottom.mas_equalTo(0);
        make.height.mas_equalTo(60);
    }];
}

/// 获取列表
- (void)requestData {
    [NET getShopListWithPage:self.lastIndex pageSize:self.pageSize userId:self.userId enable:self.enable goodsIntroduction_Like:self.searchStr success:^(id  _Nonnull responseObject) {
        NSArray *arr = [ShopModel mj_objectArrayWithKeyValuesArray:responseObject[@"content"]];
        [self downLoadImage:arr];
        if (self.lastIndex == 0) {
            [self.modelArr removeAllObjects];
        }
        [self.modelArr addObjectsFromArray:arr];
        self.tableview.modelArr = self.modelArr;
        [self.tableview reloadData];
        [self.tableview.mj_header endRefreshing];
        [self.tableview.mj_footer endRefreshing];
        self.lastIndex = [responseObject[@"lastIndex"] integerValue];
    } failure:^(NSError * _Nonnull error) {
        kShowText(error.userInfo[kHttpErrorReason]);
        self.lastIndex = 0;
        [self.tableview.mj_header endRefreshing];
        [self.tableview.mj_footer endRefreshing];
    }];
}

/// 搜索
- (void)searchData:(NSString *_Nullable)searchStr {
    self.searchStr = searchStr;
    self.lastIndex = 0;
    [self requestData];
}

/// 编辑转图
- (void)editShopInfo:(ShopModel *)model {
    PublishShopViewController *vc = [[PublishShopViewController alloc] init];
    vc.model = model;
    [self.navigationController pushViewController:vc animated:YES];
}

/// 删除商品
- (void)deleteShop:(ShopModel *)model {
    [UIAlertController showAlertInViewController:self withTitle:@"确定要删除该商品吗?" message:nil cancelButtonTitle:@"取消" destructiveButtonTitle:@"删除" otherButtonTitles:@[] tapBlock:^(UIAlertAction * _Nonnull action, NSInteger buttonIndex) {
        if (buttonIndex == UIAlertControllerBlocksDestructiveButtonIndex) {
            [YPProgressHud showHudInview:self.view];
            [NET deleteShopWithGoodsId:model.goodsId success:^(id  _Nonnull responseObject) {
                [YPProgressHud hideHudForView:self.view];
                [self.modelArr enumerateObjectsUsingBlock:^(ShopModel *obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    if ([obj.goodsId isEqualToString:model.goodsId]) {
                        [self.modelArr removeObjectAtIndex:idx];
                    }
                }];
                [self.tableview reloadData];
            } failure:^(NSError * _Nonnull error) {
                [YPProgressHud hideHudForView:self.view];
                kShowText(error.userInfo[kHttpErrorReason]);
            }];
        }
    }];
}

/// 上架下架
- (void)topOrDownShop:(ShopModel *)model {
    [YPProgressHud showHudInview:self.view];
    [NET topOrDownShopWithGoodsId:model.goodsId enable:!model.enabled success:^(id  _Nonnull responseObject) {
        [YPProgressHud hideHudForView:self.view];
        self.lastIndex = 0;
        [self requestData];
    } failure:^(NSError * _Nonnull error) {
        [YPProgressHud hideHudForView:self.view];
        kShowText(error.userInfo[kHttpErrorReason]);
    }];
}

/// 置顶
- (void)topShop:(ShopModel *)model {
    [UIAlertController showAlertInViewController:self withTitle:model.top ? @"确认取消置顶商品?" : @"确认置顶商品?" message:nil cancelButtonTitle:@"取消" destructiveButtonTitle:@"确定" otherButtonTitles:@[] tapBlock:^(UIAlertAction * _Nonnull action, NSInteger buttonIndex) {
        [YPProgressHud showHudInview:self.view];
        [NET topSetShopWithGoodsId:model.goodsId top:!model.top success:^(id  _Nonnull responseObject) {
            self.lastIndex = 0;
            [self requestData];
            [YPProgressHud hideHudForView:self.view];
        } failure:^(NSError * _Nonnull error) {
            [YPProgressHud hideHudForView:self.view];
            kShowText(error.userInfo[kHttpErrorReason]);
        }];
    }];
}

/// 下载图片
- (void)downLoadImage:(NSArray *)modelArr {
    for (ShopModel *model in modelArr) {
        for (NSString *url in model.imgUrl) {
            [[YPDownloadManager sharedDownloadManager] downloadImageWithUrl:url];
        }
        if (model.video) {
            [[YPDownloadManager sharedDownloadManager] downloadImageWithUrl:model.video];
            [[YPDownloadManager sharedDownloadManager] downloadImageWithUrl:model.videoPicUrl];
        }
    }
}

/// 售罄
- (void)soldOutData:(ShopModel *)model {
    [YPProgressHud showHudInview:self.view];
    [NET soldOutWithGoodsId:model.goodsId success:^(id  _Nonnull responseObject) {
        kShowText(@"更新完成");
        [YPProgressHud hideHudForView:self.view];
    } failure:^(NSError * _Nonnull error) {
        [YPProgressHud hideHudForView:self.view];
        kShowText(error.userInfo[kHttpErrorReason]);
    }];
}

/// 展示更新弹窗
- (void)showUpdateTipView:(ShopModel *)model {
    UpdateTipsView *v = [[UpdateTipsView alloc] init];
    [v show];
    @weakify(self)
    [v setUpdateShopBlock:^{
     @strongify(self)
        [self updateGoods:model];
    }];
    [v setCheckContentBlock:^{
       @strongify(self)
        ShopInfoViewController *vc = [[ShopInfoViewController alloc] init];
        vc.goodsId = model.goodsId;
        [self.navigationController pushViewController:vc animated:YES];
    }];
}

/// 同步更新
- (void)updateGoods:(ShopModel *)model {
    [YPProgressHud showHudInview:self.view];
    [NET updateGoodsWithGoodsId:model.goodsId success:^(id  _Nonnull responseObject) {
        kShowText(@"同步完成");
        self.lastIndex = 0;
        [self requestData];
        [YPProgressHud hideHudForView:self.view];
    } failure:^(NSError * _Nonnull error) {
        [YPProgressHud hideHudForView:self.view];
    }];
}

/// 一键转发商品
- (void)forwardGoods:(ShopModel *)model {
    [YPProgressHud showHudInview:self.view];
    [NET forwardGoodsWithGoodsId:model.goodsId success:^(id  _Nonnull responseObject) {
        kShowText(@"转发成功");
        self.lastIndex = 0;
        [self requestData];
        [YPProgressHud hideHudForView:self.view];
    } failure:^(NSError * _Nonnull error) {
        [YPProgressHud hideHudForView:self.view];
        kShowText(error.userInfo[kHttpErrorReason]);
    }];
}

/// 全选/取消
- (void)selectedBtnAction:(BOOL)isAll {
    if (isAll) {
        for (int i = 0; i < self.modelArr.count; i++) {
            NSIndexPath *indexpath = [NSIndexPath indexPathForRow:i inSection:0];
            [self.tableview selectRowAtIndexPath:indexpath animated:NO scrollPosition:UITableViewScrollPositionNone];
            ShopModel *model = self.modelArr[i];
            [self.selectedArr addObject:model.goodsId];
        }
    }else {
        for (int i = 0; i < self.modelArr.count; i++) {
            NSIndexPath *indexpath = [NSIndexPath indexPathForRow:i inSection:0];
            [self.tableview deselectRowAtIndexPath:indexpath animated:NO];
        }
        [self.selectedArr removeAllObjects];
    }
}

/// 批量删除
- (void)deleteAllData {
    NSString *str = [self.selectedArr componentsJoinedByString:@","];
    [YPProgressHud showHudInview:self.view];
    [NET deleteAllWithWithGoodsIds:str success:^(id  _Nonnull responseObject) {
        kShowText(@"编辑完成");
        [[NSNotificationCenter defaultCenter] postNotificationName:@"exitManager" object:nil];
        self.lastIndex = 0;
        [self requestData];
        [YPProgressHud hideHudForView:self.view];
    } failure:^(NSError * _Nonnull error) {
        [YPProgressHud hideHudForView:self.view];
        kShowText(error.userInfo[kHttpErrorReason]);
    }];
}

/// 批量置顶
- (void)topAllData {
    NSString *str = [self.selectedArr componentsJoinedByString:@","];
    [YPProgressHud showHudInview:self.view];
    [NET topAllWithGoodsIds:str success:^(id  _Nonnull responseObject) {
        kShowText(@"编辑完成");
        [[NSNotificationCenter defaultCenter] postNotificationName:@"exitManager" object:nil];
        self.lastIndex = 0;
        [self requestData];
        [YPProgressHud hideHudForView:self.view];
    } failure:^(NSError * _Nonnull error) {
        [YPProgressHud hideHudForView:self.view];
        kShowText(error.userInfo[kHttpErrorReason]);
    }];
}

/// 批量上下架
- (void)topDownAllData {
    NSString *str = [self.selectedArr componentsJoinedByString:@","];
    [YPProgressHud showHudInview:self.view];
    [NET topDownAllWithGoodsIds:str enable:self.enable == 1 ? 0 : 1 success:^(id  _Nonnull responseObject) {
        kShowText(@"编辑完成");
        [[NSNotificationCenter defaultCenter] postNotificationName:@"exitManager" object:nil];
        self.lastIndex = 0;
        [self requestData];
        [YPProgressHud hideHudForView:self.view];
    } failure:^(NSError * _Nonnull error) {
        [YPProgressHud hideHudForView:self.view];
        kShowText(error.userInfo[kHttpErrorReason]);
    }];
}

#pragma mark - 懒加载
- (ShopTableView *)tableview {
    if (!_tableview) {
        _tableview = [[ShopTableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableview.allowsMultipleSelectionDuringEditing = YES;
        _tableview.isMyself = self.isMyself;
        @weakify(self)
        _tableview.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            @strongify(self)
            self.lastIndex = 0;
            [self requestData];
        }];
        _tableview.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            @strongify(self)
            [self requestData];
        }];
        
        [_tableview setEditBlock:^(ShopModel * _Nonnull model) {
         @strongify(self)
            if (self.isEditShop) {
                kShowText(@"请先退出批量管理");
                return;
            }
            [self editShopInfo:model];
        }];
        [_tableview setTopDownBlock:^(ShopModel * _Nonnull model) {
           @strongify(self)
            if (self.isEditShop) {
                kShowText(@"请先退出批量管理");
                return;
            }
            [self topOrDownShop:model];
        }];
        [_tableview setTopBlock:^(ShopModel * _Nonnull model) {
           @strongify(self)
            if (self.isEditShop) {
                kShowText(@"请先退出批量管理");
                return;
            }
            [self topShop:model];
        }];
        [_tableview setDeleteBlock:^(ShopModel * _Nonnull model) {
           @strongify(self)
            if (self.isEditShop) {
                kShowText(@"请先退出批量管理");
                return;
            }
            [self deleteShop:model];
        }];
        [_tableview setShouqingBlock:^(ShopModel * _Nonnull model) {
            @strongify(self)
            if (self.isEditShop) {
                kShowText(@"请先退出批量管理");
                return;
            }
            [self soldOutData:model];
        }];
        [_tableview setUpdateBlock:^(ShopModel * _Nonnull model) {
            @strongify(self)
            [self showUpdateTipView:model];
        }];
        [_tableview setGoodsQrcodeBlock:^(ShopModel * _Nonnull model) {
            @strongify(self)
            GoodsQrCodeViewController *vc = [[GoodsQrCodeViewController alloc] init];
            vc.goodsId = model.goodsId;
            [self.navigationController pushViewController:vc animated:YES];
        }];
        [_tableview setEditTransBlock:^(ShopModel * _Nonnull model) {
            @strongify(self)
            if (!self.model.follow) {
                kShowText(@"请先关注商家");
                return;
            }
            [self editShopInfo:model];
        }];
        [_tableview setTransBlock:^(ShopModel * _Nonnull model) {
            @strongify(self)
            if (!self.model.follow) {
                kShowText(@"请先关注商家");
                return;
            }
            [self forwardGoods:model];
        }];
        
        [_tableview.subject subscribeNext:^(NSIndexPath *x) {
           @strongify(self)
            ShopModel *model = self.modelArr[x.row];
            if (self.isEditShop) {
                [self.selectedArr addObject:model.goodsId];
                return;
            }
            
            ShopInfoViewController *vc = [[ShopInfoViewController alloc] init];
            vc.goodsId = model.goodsId;
            vc.isFollow = self.model.follow;
            [self.navigationController pushViewController:vc animated:YES];
        }];
        [_tableview.deselectSubject subscribeNext:^(NSIndexPath *x) {
            @strongify(self)
            ShopModel *model = self.modelArr[x.row];
            [self.selectedArr enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if ([obj isEqualToString:model.goodsId]) {
                    [self.selectedArr removeObjectAtIndex:idx];
                }
            }];
        }];
    }
    return _tableview;
}

- (NSMutableArray *)modelArr {
    if (!_modelArr) {
        _modelArr = [NSMutableArray array];
    }
    return _modelArr;
}

- (ShopManagerBottomView *)bottomView {
    if (!_bottomView) {
        _bottomView = [[ShopManagerBottomView alloc] initWithFrame:CGRectZero withType:self.enable];
        _bottomView.alpha = 0;
        _bottomView.hidden = YES;
        @weakify(self)
        [_bottomView setSelectedAllBlock:^(BOOL isAll) {
         @strongify(self)
            [self selectedBtnAction:isAll];
        }];
        [_bottomView setDeleteBlock:^{
            @strongify(self)
            [self deleteAllData];
        }];
        [_bottomView setTopBlock:^{
            @strongify(self)
            [self topAllData];
        }];
        [_bottomView setTopDownBlock:^{
            @strongify(self)
            [self topDownAllData];
        }];
    }
    return _bottomView;
}

- (NSMutableArray *)selectedArr {
    if (!_selectedArr) {
        _selectedArr = [NSMutableArray array];
    }
    return _selectedArr;
}

- (UIView *)listView {
    return self.view;
}

@end
